<template>
  <div class="profile-container">
    <div class="profile-header">
      <div class="header-illustration"></div>

      <div class="profile-card">
        <el-card class="box-card">
          <div class="profile-header">
            <div class="left-section">
              <el-upload
                class="avatar-uploader"
                name="imgFile"
                action="http://localhost:8080/books/upload"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
              >
                <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>

              <div class="user-info">
                <h2>{{ userForm.username }}</h2>
                <p class="user-bio">{{ userForm.bio }}</p>
                <div class="account-info">
                  <span>账号：{{ userForm.account_number }}</span>
                  <el-button type="text" @click="showAddressDialog">收货地址</el-button>
                </div>
              </div>
            </div>
            <div class="right-section">
              <div class="action-buttons">
                <el-button type="primary" class="action-button add-book" @click="handleCreate">
                  <el-icon><Plus /></el-icon>
                  新增书籍
                </el-button>
                <el-button type="success" class="action-button publish-book" @click="newPage">
                  <el-icon><Upload /></el-icon>
                  发布书籍
                </el-button>
              </div>
              <div class="stats">
                <div class="stat-item" @click="goOwnersBook('all')">
                  <span class="stat-number">{{ totalBook }}</span>
                  <span class="stat-label">总书籍</span>
                </div>
                <div class="stat-item" @click="goHasPublish('published')">
                  <span class="stat-number">{{ hasPublished }}</span>
                  <span class="stat-label">已发布</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 统计数据区域 -->
          <div class="statistics-section">
            <div class="stat-item" @click="goHasPublish('published')">
              <div class="stat-number">{{ statistics.published }}</div>
              <div class="stat-label">发布的书籍</div>
            </div>
            <div class="stat-item" @click="goSaleByMe('sell')">
              <div class="stat-number">{{ statistics.sold }}</div>
              <div class="stat-label">卖出的书籍</div>
            </div>
            <div class="stat-item" @click="goBuyByMe('buy')">
              <div class="stat-number">{{ statistics.bought }}</div>
              <div class="stat-label">买到的书籍</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ statistics.comments }}</div>
              <div class="stat-label">收到的评价</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ statistics.favorites }}</div>
              <div class="stat-label">收藏的书籍</div>
            </div>
          </div>

          <!-- 订单状态区域 -->
          <div class="order-status">
            <div class="status-item">
              <div class="status-number">{{ orders.pending }}</div>
              <div class="status-label">待付款</div>
            </div>
            <div class="status-item">
              <div class="status-number">{{ orders.shipping }}</div>
              <div class="status-label">待发货</div>
            </div>
            <div class="status-item">
              <div class="status-number">{{ orders.receiving }}</div>
              <div class="status-label">待收货</div>
            </div>
            <div class="status-item" @click="goReviewing('review')">
              <div class="status-number">{{ orders.reviewing }}</div>
              <div class="status-label">待评价</div>
            </div>
            <div class="status-item">
              <div class="status-number">{{ orders.refunding }}</div>
              <div class="status-label">退款/售后</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <div class="profile-content" style="display: flex">
      <el-tabs class="custom-tabs">
        <el-tab-pane label="基本信息">
          <el-form :model="userForm" label-position="left" label-width="70px" class="profile-form">
            <el-form-item label="用户账号">
              <el-input v-model="userForm.account_number" disabled />
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="userForm.username" />
            </el-form-item>
            <el-form-item label="role">
              <el-input v-model="userForm.role" disabled />
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model="userForm.sex" placeholder="选择性别" style="width: 285px">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
            <el-form-item label="学院">
              <el-input v-model="userForm.college" placeholder="请输入学院" />
            </el-form-item>
            <el-form-item label="专业">
              <el-input v-model="userForm.major" placeholder="请输入专业" />
            </el-form-item>
            <el-form-item label="真实名称">
              <el-input v-model="userForm.realname" placeholder="请上传真实名称" />
            </el-form-item>

            <el-form-item label="电子邮箱">
              <el-input v-model="userForm.email" placeholder="请填写电子邮箱" />
            </el-form-item>

            <el-form-item label="手机号码">
              <el-input v-model="userForm.phonenumber" placeholder="请填写手机号码" />
            </el-form-item>

            <el-form-item label="QQ">
              <el-input v-model="userForm.qqnumber" placeholder="请输入QQ" />
            </el-form-item>

            <el-form-item label="个人简介" class="full-width">
              <el-input v-model="userForm.bio" type="textarea" placeholder="写点什么来介绍自己吧..." />
            </el-form-item>
            <el-form-item class="center-button">
              <el-button type="primary" @click="saveProfile">保存修改</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loginOut">退出登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="修改密码">
          <el-form :model="userForm" label-position="left" class="profile-form">
            <el-form-item label="原密码">
              <el-input v-model="userForm.oldPasswd" />
            </el-form-item>
            <el-form-item label="新密码">
              <el-input v-model="userForm.newPasswd" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updatePasswd">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <book-dialog v-model="bookForm" v-model:visible="dialogFormVisible" @ok="onOK" :type="dialogType" />
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { Edit } from '@element-plus/icons-vue';
import { ElMessage, type UploadProps } from 'element-plus';
import { API_ROOT, BookType, Nationality } from '@/types/constant';
import type { avatarResponseData, Book, ResponseData, Users } from '@/types';
import { http } from '@/services/http';
import { useUserStore } from '@/stores/user';
import router from '@/router';
import BookDialog from './BookDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import type { BookDialogType } from './BookDialog.vue';

const goReviewing = (type: any) => {
  router.push({
    name: 'order',
    params: { ownerId: userStore.userInfo.id, type: type },
  });
};

const goOwnersBook = (type: any) => {
  router.push({
    name: 'publishBook',
    params: { ownerId: userStore.userInfo.id, type: type },
  });
};

const goSaleByMe = (type: any) => {
  router.push({
    name: 'order',
    params: { ownerId: userStore.userInfo.id, type: type },
  });
};
const goBuyByMe = (type: any) => {
  router.push({
    name: 'order',
    params: { ownerId: userStore.userInfo.id, type: type },
  });
};

const goHasPublish = (type: any) => {
  router.push({
    name: 'publishBook',
    params: { ownerId: userStore.userInfo.id, type: type },
  });
};
const userStore = useUserStore();
const totalBook = ref(0);
const hasPublished = ref(0);

const originBookForm: Book = {
  owner: 0,
  book_code: '',
  name: '',
  isbn: '',
  number: 0,
  author_nationality: Nationality.Chinese,
  book_image: '',
  applicable_scope: '',
  type: BookType.Textbook,
  price: 0,
  description: '',
  notes: '',
};

const newPage = () => {
  router.push({ name: 'publishBook' });
};

const dialogType = ref<BookDialogType>('Create');
const dialogFormVisible = ref(false);
const bookForm = reactive<Book>({ ...originBookForm });
const statistics = reactive({
  published: 0,
  sold: 0,
  bought: 0,
  comments: 0,
  favorites: 0,
});

const orders = reactive({
  pending: 0,
  shipping: 0,
  receiving: 1,
  reviewing: 1,
  refunding: 0,
});

const loginOut = () => {
  localStorage.removeItem('kuaikuai');
  userStore.isLoggedIn = false;
  router.push({ name: 'login' });
};
const userForm = reactive<Users>({ ...userStore.userInfo });

const imgUrl = computed(() => {
  if (userForm.avatar) {
    return `${API_ROOT}/upload/${userForm.avatar}`;
  }
  return '';
});

const getOrders = () => {
  http.get<ResponseData>('/orders/info', { user_id: userStore.userInfo.id }).then((res) => {
    if (res.flag) {
      orders.pending = res.data.pending;
      orders.shipping = res.data.shipping;
      orders.receiving = res.data.receiving;
      orders.reviewing = res.data.reviewing;
    }
  });
};

const getStatistics = () => {
  http.get<ResponseData>('/statistics/info', { user_id: userStore.userInfo.id }).then((res) => {
    if (res.flag) {
      console.log(11223, res);

      statistics.published = res.data.published;
      statistics.sold = res.data.sold;
      statistics.bought = res.data.bought;
      statistics.comments = res.data.comments;
      statistics.favorites = res.data.favorites;
      totalBook.value = res.data.totalBooks;
      hasPublished.value = res.data.hasPublish;
      orders.reviewing = res.data.reviewing;
    }
  });
};
const handleAdd = () => {
  bookForm.owner = userStore.userInfo.id;
  http.post<ResponseData>('/books/create', bookForm).then((res) => {
    if (res.flag) {
      ElMessage({ type: 'success', message: res.msg });
      dialogFormVisible.value = false;
      getStatistics();
    } else {
      ElMessage({ type: 'error', message: res.msg || '添加失败' });
    }
  });
};
const handleEdit = () => {
  http.post<ResponseData>('/books/update', bookForm).then((res) => {
    if (res.flag) {
      ElMessage({ type: 'success', message: res.msg });
      dialogFormVisible.value = false;
    } else {
      ElMessage({ type: 'error', message: res.msg || '编辑失败' });
    }
  });
};
const onOK = () => {
  if (dialogType.value == 'Create') {
    handleAdd();
  } else {
    handleEdit();
  }
};

const handleCreate = () => {
  dialogFormVisible.value = true;
  dialogType.value = 'Create';
  Object.assign(bookForm, originBookForm);
};
const showAddressDialog = () => {};

const handleAvatarSuccess = (res: avatarResponseData) => {
  if (res.flag && res.data) {
    const param1 = {
      id: userForm.id,
      avatar: res.data,
    };
    http.post<ResponseData>('/newusers/avatar', param1);
    userForm.avatar = res.data;
    ElMessage({ type: 'success', message: res.msg });
  } else {
    ElMessage({ type: 'error', message: res.msg || '上传失败' });
  }
};
const saveProfile = () => {
  http.post<ResponseData>('/newusers/save', userForm).then((res) => {
    if (res.flag) {
      ElMessage.success('保存成功');
    }
  });
};

const updatePasswd = () => {
  if (userForm.oldPasswd !== userStore.userInfo.password) {
    ElMessage.error('原密码错误');
  } else {
    const param2 = {
      newPasswd: userForm.newPasswd,
      id: userForm.id,
    };
    console.log(111, param2);
    ``;

    http.post<ResponseData>('/newusers/updatePasswd', param2).then((res) => {
      if (res.flag) {
        ElMessage.success('密码修改成功');
        loginOut();
      }
    });
  }
};
onMounted(() => {
  getStatistics();
});
</script>

<style scoped>
/* 主容器样式 */
.profile-container {
  overflow: auto;
  box-sizing: border-box;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 100vh;
  position: relative;
}

/* 头部和背景样式 */
.header-illustration {
  background-image: url(@/assets/1112.jpg);
  background-position: center;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  width: 100%;
  z-index: -1;
  filter: blur(5px);
  transform: scale(1.1);
}

/* 卡片基础样式 */
.profile-card {
  width: 100%;
  margin: 20px auto;
  max-width: 1400px;
}

.box-card {
  background-color: rgba(255, 255, 255, 0.5) !important;
  backdrop-filter: blur(10px);
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
}

/* 用户资料头部样式 */
.profile-header {
  display: flex;
  padding: 24px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  justify-content: space-between;
}

.left-section {
  margin-left: 50px;
  display: flex;
  gap: 24px;
  align-items: center;
}

/* 头像样式 */
.avatar-uploader {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 右侧部分样式 */
.right-section {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 20px;
  margin-right: 80px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-button {
  padding: 12px 24px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stats {
  display: flex;
  gap: 24px;
  background: rgba(255, 255, 255, 0.3);
  padding: 19px 38px;
  border-radius: 8px;
  backdrop-filter: blur(5px);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 统计部分样式优化 */
.statistics-section {
  display: flex;
  justify-content: space-around;
  padding: 24px 0;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 8px;
  margin: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 0 20px;
  cursor: pointer;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

/* 订单状态样式优化 */
.order-status {
  display: flex;
  justify-content: space-around;
  padding: 24px 0;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 8px;
}

.status-item {
  text-align: center;
  cursor: pointer;
  padding: 0 20px;
}

.status-number {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.status-label {
  color: #666;
  font-size: 14px;
}

/* 表单区域样式优化 */
.profile-content {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 24px;
  margin-top: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.profile-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.profile-form :deep(.el-form-item) {
  margin-bottom: 20px;
  flex: 0 0 calc(50% - 10px);
}

.profile-form :deep(.full-width) {
  flex: 0 0 100%;
}

.profile-card:hover :deep(.el-card),
.profile-content:hover {
  background-color: rgba(255, 255, 255, 0.7);

  transform: translateY(-2px);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .left-section {
    flex-direction: column;
    align-items: center;
  }

  .statistics-section,
  .order-status {
    flex-wrap: wrap;
    gap: 16px;
  }

  .stat-item,
  .status-item {
    flex: 1 1 calc(33.33% - 16px);
    min-width: 100px;
  }

  .profile-form :deep(.el-form-item) {
    flex: 0 0 100%;
  }
}

@media (max-width: 480px) {
  .stat-item,
  .status-item {
    flex: 1 1 calc(50% - 16px);
  }
}

.account-info {
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
